package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.IsLockEnum;
import com.tanhua.common.mapper.*;
import com.tanhua.common.pojo.*;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author 寒
 * @date 2021/6/8
 * @TIME:9:56
 */
@Service
@Slf4j
public class TestSoulService {
    @Autowired
    private SoulQuestionMapper soulQuestionMapper;

    @Autowired
    private SoulQuestionOptionMapper soulQuestionOptionMapper;

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private QuestionUserLockMapper questionUserLockMapper;
    @Autowired
    private QuestionnaireResultMapper questionnaireResultMapper;
@Autowired
    QuestionnaireReportMapper questionnaireReportMapper;

@Autowired
UserInfoMapper userInfoMapper;

    public List<TestSoulVo> queryTestSoulInfo() {

        List<TestSoulVo> testSoulVos = null;
        try {
//            User user = UserThreadLocal.get();
//            Long id = user.getId();L
            Long id = 1L;

            //查询所有题
            QueryWrapper<Questionnaire> wrapper = new QueryWrapper<>();
            List<Questionnaire> questionnaires = questionnaireMapper.selectList(wrapper);

            if (questionnaires == null || questionnaires.size() == 0) {
                return null;

            }
            //查询是否加锁
            QueryWrapper<QuestionUserLock> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("user_id", id);
            List<QuestionUserLock> questionUserLocks = questionUserLockMapper.selectList(wrapper1);
            if (questionUserLocks == null || questionUserLocks.size() == 0) {
                return null;

            }
            //获取题库id

            List<Object> id1 = CollUtil.getFieldValues(questionnaires, "id");
            QueryWrapper<SoulQuestion> wrapper2 = new QueryWrapper<>();
            wrapper2.in("questionnaire_id", id1);
            List<SoulQuestion> soulQuestions = soulQuestionMapper.selectList(wrapper2);

            if (soulQuestions == null || soulQuestions.size() == 0) {
                return null;

            }

            //查询选项
            QueryWrapper<SoulQuestionOption> wrapper3 = new QueryWrapper<>();
            List<SoulQuestionOption> soulQuestionOptions = soulQuestionOptionMapper.selectList(wrapper3);
            testSoulVos = new ArrayList<>();
            if (soulQuestionOptions == null || soulQuestionOptions.size() == 0) {
                return null;

            }

            for (Questionnaire questionnaire : questionnaires) {
                TestSoulVo testSoulVo = new TestSoulVo();
                testSoulVo.setId(questionnaire.getId().toString());
                testSoulVo.setName(questionnaire.getName());
                testSoulVo.setCover(questionnaire.getCover());
                testSoulVo.setLevel(questionnaire.getLevel().toString());
                testSoulVo.setStar(questionnaire.getStar());
                ArrayList<Questions> questions = new ArrayList<>();
                testSoulVo.setQuestions(questions);
                for (QuestionUserLock questionUserLock : questionUserLocks) {

                    if (questionnaire.getId() == questionUserLock.getQuestionnaireId()) {
                        if (questionUserLock.getIsLock() != null) {
                            testSoulVo.setIsLock(questionUserLock.getIsLock());
                            break;
                        } else {
                            testSoulVo.setIsLock(IsLockEnum.UnLock.getValue());

                        }

                    }

                }
                testSoulVo.setReportId("待定");
                for (SoulQuestion soulQuestion : soulQuestions) {
                    if (questionnaire.getId() == soulQuestion.getQuestionnaireId()) {
                        //构建问题
                        Questions qqq = Questions.builder().id(soulQuestion.getId()).question(soulQuestion.getStem()).build();
                        //封装本题的选项
                        ArrayList<Options> options = new ArrayList<>();
                        qqq.setOptions(options);
                        for (SoulQuestionOption soulQuestionOption : soulQuestionOptions) {
                            //选项够了,跳出循环
                            if (soulQuestionOption.getQuestionId() == qqq.getId()) {
                                options.add(new Options(soulQuestionOption.getId(), soulQuestionOption.getContent()));
                            }
                        }

                        //加入到问题集合
                        questions.add(qqq);
                    }
                }

                testSoulVos.add(testSoulVo);
            }
        } catch (Exception e) {
            log.error("测灵魂数据查询失败", e);
        }


        return testSoulVos;
    }

    public String testSoulScore(List<Answer> answers) {
//        User user = UserThreadLocal.get();
//        Long id = user.getId();


        try {

            int sum = 0;
            for (Answer answer : answers) {
                String optionId = answer.getOptionId();
                String questionId = answer.getQuestionId();

                QueryWrapper<SoulQuestionOption> wrapper = new QueryWrapper<>();
                wrapper.eq("id", optionId);
                wrapper.eq("question_id", questionId);
                SoulQuestionOption soulQuestionOption = soulQuestionOptionMapper.selectOne(wrapper);
                if (soulQuestionOption != null) {
                    sum += soulQuestionOption.getScore();
                }
            }
            QueryWrapper<QuestionnaireResult> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("questionnaire_id", answers.get(1).getQuestionId());
            if (sum > 0 && sum <= 20) {
                wrapper1.eq("scope", "0,20");
            } else if (sum > 20 && sum <= 40) {
                wrapper1.eq("scope", "21,40");
            } else if (sum > 41 && sum <= 55) {
                wrapper1.eq("scope", "41,55");
            } else if (sum > 56 && sum <= 100) {
                wrapper1.eq("scope", "56,100");
            }
            QuestionnaireResult questionnaireResult = questionnaireResultMapper.selectOne(wrapper1);
            //这里id写死方便测试
//            UUID uuid = UUID.randomUUID();
//            String s = StrUtil.removeAll(uuid.toString(), "-");
//            System.out.println(s);
            QuestionnaireReport build = QuestionnaireReport.builder().userId(2).conclusionId(questionnaireResult.getId()%4).
                    cover(questionnaireResult.getCover()).build();
            build.setId(5);
            if (build.getConclusionId() == 1) {
                build.setExtroversion(80);
                build.setAbstraction(80);
                build.setJudgement(70);
                build.setRetionality(90);

            } else if (build.getConclusionId() == 2) {
                build.setExtroversion(70);
                build.setAbstraction(90);
                build.setJudgement(80);
                build.setRetionality(90);

            } else if (build.getConclusionId() == 3) {
                build.setExtroversion(70);
                build.setAbstraction(80);
                build.setJudgement(70);
                build.setRetionality(90);

            } else if (build.getConclusionId() == 4) {
                build.setExtroversion(80);
                build.setAbstraction(90);
                build.setJudgement(70);
                build.setRetionality(70);

            }

           int  insert = questionnaireReportMapper.insert(build);
            if (insert==1)
            {
                return build.getId().toString();
            }
        } catch (Exception e) {
            log.error("查询错误", e);
        }
        return null;
    }

    public TestResultVo testResult(Long id) {
        TestResultVo testResultVo = new TestResultVo();
        List<Dimensions> dimensionList = new ArrayList<>();
        //通过id获取报告里面的数据
        QuestionnaireReport questionnaireReport = questionnaireReportMapper.selectById(id);
        Integer concludeId = questionnaireReport.getConclusionId();

        dimensionList.add(new Dimensions("extroversion",questionnaireReport.getExtroversion().toString()));
        dimensionList.add(new Dimensions("judgement",questionnaireReport.getJudgement().toString()));
        dimensionList.add(new Dimensions("abstraction",questionnaireReport.getAbstraction().toString()));
        dimensionList.add(new Dimensions("rationality",questionnaireReport.getRetionality().toString()));

        //保存到testResultVo里面
        QuestionnaireResult questionnaireResult = questionnaireResultMapper.selectById(concludeId);
        testResultVo.setConclusion(questionnaireResult.getContent());
        testResultVo.setCover(questionnaireResult.getCover());
        testResultVo.setDimensions(dimensionList);

        //通过resultId查询报告表，获取所有的用户，存到集合里
        QueryWrapper<QuestionnaireReport> queryWrapper = new QueryWrapper();
        queryWrapper.eq("result_id",concludeId);
        List<QuestionnaireReport> questionnaireReports = questionnaireReportMapper.selectList(queryWrapper);
        List<Long> userIds = new ArrayList<>();
        for (QuestionnaireReport report : questionnaireReports) {
            userIds.add(Convert.toLong(report.getUserId()));
        }


        //查询所有用户的完整信息
        QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper();
        queryWrapper1.in("user_id",userIds);
        List<UserInfo> userInfos = userInfoMapper.selectList(queryWrapper1);

        ArrayList<SimilarYou> similarYouList = new ArrayList<>();
        //如果是当前用户就跳过，否则添加到相似的人集合里
        for (UserInfo userInfo : userInfos) {
            if(UserThreadLocal.get().getId().equals(userInfo.getUserId())){
                continue;
            }
            similarYouList.add(new SimilarYou(userInfo.getUserId(),userInfo.getLogo()));
        }

        testResultVo.setSimilarYou(similarYouList);
        return testResultVo;



    }
}


